package com.distribution.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.framework.config.ServerConfig;
import com.distribution.system.domain.entity.ImgUpload;
import com.distribution.system.domain.req.ImgUploadMoveToReq;
import com.distribution.system.service.ImgUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: GodLu
 * @create: 2024-11-09 15:10
 * @description: 图片上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/imgUpload")
public class ImgUploadController extends BaseController {
    @Value("${swagger.pathMapping}")
    private String pathMapping;
    @Resource
    ServerConfig serverConfig;
    @Resource
    private ImgUploadService imgUploadService;

    @GetMapping("/getImgUploadListByTypeId/{typeId}")
    public AjaxResult getImgTypeList(@PathVariable Integer typeId){
        List<ImgUpload> list = imgUploadService.lambdaQuery().eq((typeId != 0), ImgUpload::getImgTypeId, typeId).orderByAsc(ImgUpload::getUpdateTime).list();
        list.forEach(f -> {
            f.setImgPath(serverConfig.getUrl() + pathMapping + f.getImgPath());
        });
        return success(list);
    }

    @Transactional
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ImgUpload imgUpload){
        imgUpload.setCreateTime(LocalDateTime.now());
        imgUpload.setUpdateTime(LocalDateTime.now());
        return imgUploadService.save(imgUpload) ? success() : error("添加失败");
    }

    @DeleteMapping("/{ids}")
    public AjaxResult del(@PathVariable int[] ids){
        List<Integer> idList = new ArrayList<>();
        for (int id : ids) {
            idList.add(id);
        }
        return imgUploadService.removeByIds(idList) ? success() : error("删除失败");
    }

    @Transactional
    @PostMapping("/moveImgToType")
    public AjaxResult updateById(@RequestBody @Valid ImgUploadMoveToReq imgUploadMoveToReq){
        System.out.println("imgUploadMoveToReq = " + imgUploadMoveToReq);
        boolean updated = imgUploadService.lambdaUpdate().in(ImgUpload::getId, imgUploadMoveToReq.getIdList())
                .set(ObjectUtil.isNotNull(imgUploadMoveToReq.getImgTypeId()), ImgUpload::getImgTypeId, imgUploadMoveToReq.getImgTypeId()).update();
        return updated ? success() : error("更新失败");
    }
}
